var core = require('core');
var db = core.db;
var send = core.send;
var qrcode = function(req, res, next){

    var body = req.body;
    var type = body.type;
    var qid = body.qid;
    var url = body.url;
    var msg = body.msg;
    var time = body.time;
    var ticket = body.ticket;
    var SEND;
    // db.schema[type].findOne({token: token}, "-_id -__v -expires", function(err, doc){
    //     if(err){
    //         SEND = new send(100000);
    //         console.error(err);
    //     }else{
    //         SEND = new send(0);
    //         if(doc && doc.data){
    //             doc.data = doc.data;
    //         };
    //         SEND.docs = doc;
    //     };
    //
    //     res.send(SEND);
    // });
    if(type == "get"){
        var query = {};
        if(qid)
            query.qid = JSON.parse(qid);
        if(msg)
            query.msg = msg;
        if(time)
            query.time = JSON.parse(time);

        db.schema.Qrcode.find(query, "-_id -__v", function(err, doc){
            if(err)
                SEND = new send(100000);
            else{
                SEND = new send(0);
                SEND.docs = doc.length === 1 ? doc[0] : doc;
            };
            res.send(SEND);
        });
    }else if(type == "set"){
        var Qrcode = new db.schema.Qrcode({qid: qid, url: url, msg: msg, time: time, ticket: ticket});
        Qrcode.save(function(err, doc){
            if(err)
                SEND = new send(100000);
            else{
                SEND = new send(0);
                SEND.docs = doc;
            };
            res.send(SEND);
        });
    }else if(type == "update"){
        var update = {};
        if(msg)
            update.msg = msg;
        if(url)
            update.url = url;

        var options = {
            upsert : false
        };
        db.schema.Qrcode.findOneAndUpdate({qid: qid}, update, options, function(err, doc){
            if(err)
                SEND = new send(100000);
            else{
                SEND = new send(0);
                SEND.docs = doc;
            };
            res.send(SEND);
        });
    }else if(type == "count"){
        var query = {};
        try{
            if(qid)
                query.qid = JSON.parse(qid);
            if(msg)
                query.msg = msg;
            if(time)
                query.time = JSON.parse(time);
        }catch(err){
            console.log(err,'=====')
        }

        console.log(query,'===========!!!!!!');
        db.schema.Qrcode.count(query, function(err, doc){
            if(err)
                SEND = new send(100000);
            else{
                SEND = new send(0);
                SEND.docs = doc;
            };
            res.send(SEND);
        });
    }

};

module.exports = qrcode;
